package com.da.lon.wang.xlg.http;

import android.content.Context;
import android.text.TextUtils;
import android.widget.Toast;

import com.da.lon.wang.xlg.MyApplication;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.osell.selection.util.DeviceUuidFactory;

import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;

import org.apache.http.HttpEntity;
import org.json.JSONObject;

/**
 * http访问网络公共类
 *
 * @author qinhao
 * @since 2014年12月26日16:03:12
 */

public class HttpLoader<T> {

    private String mUrl;
    private FinalHttp mFinalHttp;
    private Context mContext;
    private OnWebLoadListener<T> mOnWebLoadListener;
    private Class<T> mClassOfT;
    private AjaxCallBack<Object> ajaxCallBack = new AjaxCallBack<Object>() {

        public void onStart() {
            if (null != mOnWebLoadListener) {
                mOnWebLoadListener.OnStart();
            }
        }

        ;

        public void onFailure(Throwable t, int errorNo, String strMsg) {
            if (null != mOnWebLoadListener) {
                mOnWebLoadListener.OnError(strMsg);
            }
        }

        ;

        public void onSuccess(Object t) {
            if (null != mOnWebLoadListener) {
                try {
                    mOnWebLoadListener.onSuccess(new Gson().fromJson(
                            t.toString(), mClassOfT));
                } catch (JsonSyntaxException e) {
                    mOnWebLoadListener.OnError("解析失败");
                }
            }
        }

        ;
    };
    /**
     * 回复专用
     */

    private OnWebLoadListenerReplay<T> onWebLoadListenerReplay;
    private AjaxCallBack<Object> ajaxCallBackReplay = new AjaxCallBack<Object>() {

        public void onStart() {
            if (null != onWebLoadListenerReplay) {
                onWebLoadListenerReplay.OnStart();
            }
        }

        ;

        public void onFailure(Throwable t, int errorNo, String strMsg) {
            if (null != onWebLoadListenerReplay) {
                onWebLoadListenerReplay.OnError(strMsg);
            }
        }

        ;

        public void onSuccess(Object t) {
            if (null != onWebLoadListenerReplay) {
                try {
                    JSONObject jsonObject = new JSONObject(t.toString());
                    JSONObject result = jsonObject.optJSONObject("result");
                    if (result != null) {
                        JSONObject html = result.optJSONObject("html");
                        onWebLoadListenerReplay.onSuccess(
                                new Gson().fromJson(t.toString(), mClassOfT),
                                html.toString());
                    } else {
                        onWebLoadListenerReplay.onSuccess(
                                new Gson().fromJson(t.toString(), mClassOfT),
                                "");
                    }

                } catch (JsonSyntaxException e) {
                    onWebLoadListenerReplay.OnError("解析失败");
                } catch (Exception e) {
                    onWebLoadListenerReplay.OnError("解析失败");
                }
            }
        }
    };

    public HttpLoader(Context context, String url, Class<T> classOfT) {
        mFinalHttp = MyApplication.getHttp();
        mFinalHttp.configTimeout(10 * 1000);
        mFinalHttp.configRequestExecutionRetryCount(0);
        mFinalHttp
                .addHeader(
                        "User-Agent",
                        "Mozilla/5.0 (Linux; Android 4.3; Nexus 10 Build/JSS15Q) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2307.2 Safari/537.36");
        mContext = context;
        mClassOfT = classOfT;
        mUrl = url;
    }

    public HttpLoader(Context context, String url, Class<T> classOfT,
                      int timeOut) {
        mFinalHttp = MyApplication.getHttp();
        mFinalHttp.configTimeout(timeOut);
        // 请求错误重试次数
        mFinalHttp.configRequestExecutionRetryCount(0);
        // 配置http请求头
        mFinalHttp
                .addHeader(
                        "User-Agent",
                        "Mozilla/5.0 (Linux; Android 4.3; Nexus 10 Build/JSS15Q) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2307.2 Safari/537.36");
        mContext = context;
        mClassOfT = classOfT;
        mUrl = url;
    }

    public void setManagerListener(OnWebLoadListener<T> onWebLoadListener) {
        if (MyApplication.isNetworkAvailable(mContext)) {
            mOnWebLoadListener = onWebLoadListener;
        } else {
            Toast.makeText(mContext, "网络连接失败", Toast.LENGTH_SHORT).show();
        }
    }

    public void loadData() {
        mFinalHttp.get(mUrl, ajaxCallBack);
    }

    public void loadData(HttpEntity httpEntity) {
        mFinalHttp.post(mUrl, httpEntity, "application/json", ajaxCallBack);
    }

    public void loadData(AjaxParams params) {
        if (!params.getParamString().contains("deviceId=")) {
            params.put("deviceId", new DeviceUuidFactory(MyApplication.getInstance()).getDeviceUuid().toString());
        }
        if (!params.getParamString().contains("?id=")
                && !"".equals(MyApplication.getUserId())
                && !params.getParamString().contains("&id=")) {
            params.put("id", MyApplication.getUserId());
        }
        if (!params.getParamString().contains("user_key=")
                && !"".equals(MyApplication.getUserKey())) {
            params.put("user_key", MyApplication.getUserKey());
        }
        if (!params.getParamString().contains("shop_id=")
                && !"".equals(MyApplication.getShopId())) {
            params.put("shop_id", MyApplication.getShopId());
        }
        if (!params.getParamString().contains("lan=")) {
            String language = MyApplication.getInstance().getResources().getConfiguration().locale.getLanguage();
            if (TextUtils.equals("zh", language)) {
                language = "cn";
            }
            params.put("lan", language);
        }
        mFinalHttp.post(mUrl, params, ajaxCallBack);
    }

    public void loadData(HttpEntity httpEntity, String contentType) {
        mFinalHttp.post(mUrl, httpEntity, contentType, ajaxCallBack);
    }

    public void loadReplayData(AjaxParams params) {
        mFinalHttp.post(mUrl, params, ajaxCallBackReplay);
    }

    public void setReplayManagerListener(
            OnWebLoadListenerReplay<T> onWebLoadListenerReplay) {
        this.onWebLoadListenerReplay = onWebLoadListenerReplay;
    }

    public interface OnWebLoadListener<T> {
        public void OnStart();

        public void OnError(String error);

        public void onSuccess(T t);

    }

    public interface OnWebLoadListenerReplay<T> {
        public void OnStart();

        public void OnError(String error);

        public void onSuccess(T t, String result);

    }
}
